package com.dcy.daily.common.configuration.snowflake;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;

/**
 * 雪花算法优化，初始化datacenterId和workId
 *
 * modify liyamin  2021/4/27 16:27
 */
@Component
@ConditionalOnProperty(prefix = "snowflake", name = "enabled", havingValue = "true")
@DependsOn("springUtil")
public class SnowflakeComponent implements DisposableBean {
    private static final Logger logger = LoggerFactory.getLogger(SnowflakeComponent.class);

    public static int datacenterId;

    public static int workId;

    private final long workerIdBits = 5L;

    private final long datacenterIdBits = 5L;


    public  void setDatacenterId(int datacenterId) {
        SnowflakeComponent.datacenterId = datacenterId;
    }

    public  void setWorkId(int workId) {
        SnowflakeComponent.workId = workId;
    }

    public static int getDatacenterId() {
        return datacenterId;
    }

    public static int getWorkId() {
        return workId;
    }

    private static volatile SnowflakeIdWorker instance;

    public static SnowflakeIdWorker getInstance() {
        if (instance == null) {
            synchronized (SnowflakeIdWorker.class) {
                if (instance == null) {
                    instance = new SnowflakeIdWorker(workId, datacenterId);
                }
            }
        }
        return instance;
    }


    @Override
    public void destroy() throws Exception {

    }
}